package com.ajie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ajie.entity.BaseEntity;
import com.ajie.entity.FoodType;
import com.ajie.service.FoodTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ajie.entity.Food;
import com.ajie.mapper.FoodMapper;
import com.ajie.service.FoodService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 食物信息;(food)表服务实现类
 * @author: ajie
 * @date : 2024-7-27
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements FoodService {

    @Resource
    private FoodTypeService typeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(List<Food> maps) {
        for (Food map : maps) {
            // 获取食物类型
            LambdaQueryWrapper<FoodType> lqw = new LambdaQueryWrapper<>();
            lqw.eq(FoodType::getTitle, map.getTypeId());
            lqw.select(FoodType::getId);
            // 得到食物类型
            String typeId = typeService.getObj(lqw, Object::toString);
            if (StrUtil.isNotBlank(typeId)) {
                map.setTypeId(typeId);
            } else {
                FoodType type = new FoodType();
                type.setTitle(map.getTypeId());
                type.setIcon("");
                if (typeService.save(type)) {
                    map.setTypeId(type.getId());
                }
            }
            // 获取食物是否存在，存在则修改，不存在添加
            LambdaQueryWrapper<Food> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(Food::getTitle, map.getTitle()).eq(Food::getTypeId, map.getTypeId());
            lqw2.last("LIMIT 1");
            Food food = super.getOne(lqw2);
            if (food != null) {
                map.setId(food.getId());
            }
        }
        return super.saveOrUpdateBatch(maps);
    }
}